<template>
  <!-- AddAuthor 组件 -->
  <!--  <AddAuthor  @author-added="handleAuthorAdded" />-->
  <el-button type="primary" @click="handleSubmitData">确认选课</el-button>
  <el-table :data="tableData.value" @selection-change="handleSelectionChange"
            border type="index" style="width: 100%" >
    <el-table-column
        type="selection"
        width="55">
    </el-table-column>
    <el-table-column
        v-for="(value, key) in get_reportInfo"
        :key="key"
        :prop="key"
        :label="value.verbose_name"
        :width="120"
    ></el-table-column>
  </el-table>
</template>

<script setup>
import {ref, onMounted, watchEffect, onBeforeUnmount, reactive} from 'vue';
import setting from '@/setting.js';
import eventBus from "@/event-bus.js";
import {ElMessage,ElMessageBox} from "element-plus";
import AddData from "@/components/Main/ReportManagement/AddData.vue";
import EditData from "@/components/Main/ReportManagement/EditData.vue";
import global, {jsonApi} from "@/global.js";

const props = defineProps({
  tableType: {
    type: String,
    required: true
  }
});

// State
const reportInfo = ref({});
const get_reportInfo = ref({});
const tableData = reactive([]);

const fileInput = ref(null);
let currentRow = ref(null);
onMounted(() => {
});

onBeforeUnmount(() => {
});
const handleTableTypeUpdate = (type) => {
  if (type) {
    // 当接收到新的tableType时，进行数据加载等操作
    console.log('Received tableType:', type);
    // 这里调用getData等函数来处理新类型的数据加载
  }
};
// Methods
//初始化函数
const getDataWithAccessToken = async () => {
  //根据当前时间获取年份和学期
  const requestBody = {
    year:"2023-2024学年",
    semester:"第二学期",
  };

  try {

    const response = await jsonApi('/courseselection/get/',JSON.stringify(requestBody));

    const data = await response.json();
    orgTableData = JSON.parse(JSON.stringify(data));
    if (!response.ok) {

        showError('获取数据失败', data.error, 2000);

    } else {
      tableData.value = data; // 假设返回的数据直接用于表格

    }
  } catch (error) {
    console.error(error);
  }
};
const getCourseseInfo = async () => {
  //获取时需要排除的字段
  if(!localStorage.getItem('courseinfo')) {

    const response = await jsonApi('/courseselection/getmodelfields/',"");
    const data = await response.json();
    if (response.ok) {
      localStorage.setItem('courseinfo', JSON.stringify(data));
      await getCourseseInfo();
    } else {
         ElMessage(
             {
               message: '获取数据失败',
               type: 'error',
               duration: 2000,
             }
         );
    }
  }
  //将字符串转为对象
  reportInfo.value = JSON.parse(localStorage.getItem('courseinfo'));
  get_reportInfo.value =reportInfo.value['CourseSelection']
  const get_excludeFields = ['model_name', 'attachment'];
  // 使用 forEach 循环来遍历对象的所有键
  get_excludeFields.forEach(field => {
    // 如果报告信息中存在要排除的字段，则删除它
    if (get_reportInfo.value.hasOwnProperty(field)) {
      delete get_reportInfo.value[field];
    }
  });
  console.log(get_reportInfo.value);
}
const currentRows=ref([]);
const handleSelectionChange=(selection) => {
  currentRows.value = selection;
}

//提交选课
const handleSubmitData = async () => {
  /*
  * /courseselection/choose/
{
    "course_selection_ids":[1,2,3,4],
}
  */
  try {
    const requestBody = {
      course_selection_ids: currentRows.value.map(row => row.id),
    }
    const response = await jsonApi('/courseselection/choose/',JSON.stringify(requestBody));
    if (response.ok) {
      ElMessage({
        message: '选课成功',
        type: 'success',
      });
      // 刷新表格数据
      await getDataWithAccessToken(props.tableType);
    } else {
      const data = await response.json();
      showError('选课失败', data.error, 2000);
    }
  } catch (e) {
    ElMessage({
      message: '选课失败',
      type: 'error',
    });
  }


};



//刷新表格获取新数据
const refreshTable = async () => {
      // 获取新的数据
      await getDataWithAccessToken();
};


watchEffect(async () => {

        await getCourseseInfo();
        await getDataWithAccessToken();

    });


function showError(message, error, duration) {
      console.error(message, error);
      // 实现错误展示逻辑，例如使用通知组件
    }

</script>

<style>
/* 添加样式 */
</style>
